﻿using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernateEntities.Entities;

namespace NHibernateFactory
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    InitializeSessionFactory();
                }
                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            const string connectionString = "Data Source=BUYCHU-PC;Initial Catalog=INV-4;User ID=wichan;Password=1234";
            _sessionFactory = Fluently.Configure()
                      .Database(MsSqlConfiguration.MsSql2008.ConnectionString(@connectionString))
                      .Mappings(m => m.AutoMappings.Add(CreateAutomappings))
                      //.ExposeConfiguration(BuildSchema)
                      .BuildSessionFactory();
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(false, true);
        }

        private static AutoPersistenceModel CreateAutomappings()
        {
            // This is the actual automapping - use AutoMap to start automapping,
            // then pick one of the static methods to specify what to map (in this case
            // all the classes in the assembly that contains Employee), and then either
            // use the Setup and Where methods to restrict that behaviour, or (preferably)
            // supply a configuration instance of your definition to control the automapper.
            return AutoMap.AssemblyOf<Media>()
                .Conventions.Add<CascadeConvention>()
                .Where(t => t.Namespace != null && t.Namespace.EndsWith("Entities"));
        }
    }
}
